﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Tilemaps;

public class TileSpawner : MonoBehaviour
{

    public Tilemap floorLayer;
    public Tilemap unWalkableLayer;

    public GameObject spawnLayer;
    public GameObject spawnTilePrefab;
    
    private Vector3 m_spawnLayerPosition;
    
    // Start is called before the first frame update
    void Start()
    {
        m_spawnLayerPosition = spawnLayer.transform.position;
        SpawnTiles();
    }

    private void SpawnTiles()
    {
        // 1 根据预设的地板层找出需要生成Tile的坐标
        Vector3[] floorTilesLocation = getTileMapUsedTileLocation(floorLayer, m_spawnLayerPosition.x, m_spawnLayerPosition.y);
        // 2 根据预设的不可破坏掩体层找出Tile坐标
        Vector3[] blockTilesLocation = getTileMapUsedTileLocation(unWalkableLayer, m_spawnLayerPosition.x, m_spawnLayerPosition.y);
        // 3 让地板层做差集 除去无法移动到的坐标
        var needGenerateTilesLocation = floorTilesLocation.Except(blockTilesLocation);
        
        // 4 根据坐标生成Tile
        foreach (Vector3 pos in needGenerateTilesLocation)
        {
            Instantiate(spawnTilePrefab, new Vector3(pos.x, pos.y), Quaternion.identity, spawnLayer.transform);
        }
    }

    private Vector3[] getTileMapUsedTileLocation(Tilemap tilemap, float xOffset = 0, float yOffset = 0)
    {
        List<Vector3> tempList = new List<Vector3>();

        foreach (Vector3 pos in TilePositionGenerator(tilemap, xOffset, yOffset))
        {
            tempList.Add(pos);
        }
        
        return tempList.ToArray();
    }
    
    private IEnumerable<Vector3> TilePositionGenerator(Tilemap tilemap, float xOffset = 0, float yOffset = 0)
    {
        BoundsInt bounds = tilemap.cellBounds;
        TileBase[] tileBases = tilemap.GetTilesBlock(bounds);

        for (int x = 0; x < bounds.size.x; x++)
        {
            for (int y = 0; y < bounds.size.y; y++)
            {
                var tile = tileBases[x + y * bounds.size.x];
                if (tile)
                {
                    Vector3Int pos = new Vector3Int(x, y, 0);
//                    Vector3 newPos = new Vector3(x, y, 0);
                    Vector3 newPos = tilemap.CellToWorld(pos);

                    newPos.x += xOffset + bounds.position.x;
                    newPos.y += yOffset + bounds.position.y;
                    
                    yield return newPos;
                }
            }
        }
    }
    
}
